import { defineStore } from 'pinia'
import { authAPI } from '@/utils/api'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token') || null,
    loading: false,
    error: null
  }),
  
  getters: {
    isAuthenticated: (state) => !!state.token,
    userInfo: (state) => state.user
  },
  
  actions: {
    // 设置token
    setToken(token) {
      this.token = token
      if (token) {
        localStorage.setItem('token', token)
      } else {
        localStorage.removeItem('token')
      }
    },
    
    // 设置用户信息
    setUser(user) {
      this.user = user
      if (user) {
        localStorage.setItem('user', JSON.stringify(user))
        // 同时保存userId到localStorage，方便其他组件直接获取
        localStorage.setItem('userId', user.id.toString())
      } else {
        localStorage.removeItem('user')
        localStorage.removeItem('userId')
      }
    },
    
    // 登录
    async login(credentials) {
      this.loading = true
      this.error = null
      
      try {
        const response = await authAPI.login(credentials)
        this.setToken(response.token)
        this.setUser(response.user)
        this.loading = false
        return response
      } catch (error) {
        this.error = error.response?.data?.message || '登录失败'
        this.loading = false
        throw error
      }
    },
    
    // 注册
    async register(userData) {
      this.loading = true
      this.error = null
      
      try {
        const response = await authAPI.register(userData)
        this.loading = false
        return response
      } catch (error) {
        this.error = error.response?.data?.message || '注册失败'
        this.loading = false
        throw error
      }
    },
    
    // 获取当前用户信息
    async fetchCurrentUser() {
      if (!this.isAuthenticated) return
      
      this.loading = true
      this.error = null
      
      try {
        const response = await authAPI.getCurrentUser()
        this.setUser(response.user || response)
        this.loading = false
        return response
      } catch (error) {
        // 如果获取用户信息失败，可能是token过期，清除token
        this.logout()
        this.error = '获取用户信息失败，请重新登录'
        this.loading = false
        throw error
      }
    },
    
    // 登出
    logout() {
      this.setToken(null)
      this.setUser(null)
      this.error = null
    },
    
    // 从localStorage初始化用户信息
    initializeUser() {
      const storedUser = localStorage.getItem('user')
      if (storedUser) {
        try {
          this.setUser(JSON.parse(storedUser))
        } catch (error) {
          console.error('解析用户信息失败:', error)
          this.setUser(null)
        }
      }
    },
    
    // 清除错误信息
    clearError() {
      this.error = null
    }
  }
})